package com.ctsi.organise.service;


import com.ctsi.commons.util.UtilValidate;
import com.ctsi.commons.util.id.UUIDGenerator;
import com.ctsi.commons.util.response.Page;
import com.ctsi.framework.mybatis.support.MybatisGenericDao;
import com.ctsi.organise.dto.SupportUserDTO;
import com.ctsi.organise.entity.UserExpertEntity;
import com.ctsi.security.ISecurity;
import com.ctsi.system.api.IDictionaryTreeData;
import com.ctsi.system.service.api.DictionayTreeServiceProxy;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

/**
 * UserExpertEntity Service 类
 *
 * @author liuhx
 * @description UserExpertEntity
 * @created Thu Sep 27 14:20:28 CST 2018
 */
@Service
public class UserExpertEntityService {
    private static final Logger logger = LoggerFactory.getLogger(UserExpertEntityService.class);
    @Autowired
    private MybatisGenericDao dao;
    @Autowired
    private DictionayTreeServiceProxy dictionayTreeServiceProxy;
    @Autowired
    private ISecurity iSecurity;

    /**
     * 添加
     */
    public void insertUserExpertEntity(UserExpertEntity userExpertEntity) {
        if (UtilValidate.isEmpty(userExpertEntity.getId())) {
            userExpertEntity.setId(UUIDGenerator.getId());
        }
        logger.debug("insert {}", userExpertEntity);
        dao.insert(userExpertEntity);
    }

    public void  insertUserExperList(List<UserExpertEntity> users){
        users.stream().forEach(userExpertEntity -> {
            Map<String,Object> params = new HashMap<>();
            params.put("userId",userExpertEntity.getUserId());
            params.put("expertTag",userExpertEntity.getExpertTag());
            long count = (long) this.dao.queryForObject(UserExpertEntity.class.getName()+".count",params);
            if (count == 0L) {
                this.insertUserExpertEntity(userExpertEntity);
            }
        });
    }

    /**
     * 动态更新
     */
    public int updateUserExpertEntityByPKSelective(UserExpertEntity userExpertEntity) {
        logger.debug("updateByPrimaryKeySelective {}", userExpertEntity);
        return dao.update(UserExpertEntity.class.getName() + ".updateByPrimaryKeySelective", userExpertEntity);
    }

    /**
     * 删除专家
     * @param userId
     */
    public void deleteByUserId(String userId){
         dao.delete(UserExpertEntity.class.getName() +".deleteByUserId", userId);
    }

    /**
     * 更新
     */
    public int updateUserExpertEntity(UserExpertEntity userExpertEntity) {
        logger.debug("update {}", userExpertEntity);
        return dao.update(userExpertEntity);
    }

    public UserExpertEntity editUserExpertEntityById(String id) {
        if (UtilValidate.isEmpty(id)) {
            return null;
        }
        logger.debug("editById {}", id);
        return (UserExpertEntity) dao.queryForObject(UserExpertEntity.class.getName() + ".edit", id);
    }

    /**
     * 根据ID查找 UserExpertEntity对象
     */
    public UserExpertEntity findUserExpertEntityById(String id) {
        if (UtilValidate.isEmpty(id)) {
            return null;
        }
        logger.debug("findById {}", id);
        return dao.get(UserExpertEntity.class, id);
    }

    /**
     * 删除UserExpertEntity对象
     */
    public int removeUserExpertEntity(String id) {
        if (UtilValidate.isNotEmpty(id)) {
            return dao.delete(UserExpertEntity.class.getName() + ".delete", id);
        }
        //return dao.remove(id);
        return 0;
    }

    /**
     * 详细页查询
     */
    public Map<String, Object> findByDetail(String id) {
        return (Map<String, Object>) dao.queryForObject(UserExpertEntity.class.getName() + ".findByDetail", id);
    }

    /**
     * 多条件查询结果
     */
    public Page<UserExpertEntity> findByMulitCondition(Map<String, Object> param, int start, int pageSize) {
        logger.debug("findByMulitCondition {}", param);
        if (pageSize < 0 || pageSize > 2000) {
            pageSize = Page.DEFAULT_PAGE_SIZE;
        }
        if (start != -1) {
            return dao.queryPage(UserExpertEntity.class.getName() + ".selectMulitCondition", param, start, pageSize);
        } else {
            throw new RuntimeException("参数不正确 !!");
        }
    }


    public Page<UserExpertEntity> findUser(Map<String, Object> param, int start, int pageSize){
        logger.debug("findByMulitCondition {}", param);
        if (pageSize < 0 || pageSize > 2000) {
            pageSize = Page.DEFAULT_PAGE_SIZE;
        }
        if (start != -1) {
            return dao.queryPage(UserExpertEntity.class.getName() + ".selectUser", param, start, pageSize);
        } else {
            throw new RuntimeException("参数不正确 !!");
        }
    }

    /**
     *
     * @param param
     * @param start
     * @param pageSize
     * @return
     */
    public Page<SupportUserDTO> findSupportRoleUser(Map<String, Object> param, String userLoginId, int start, int pageSize){
        logger.debug("findSupportRoleUser {}", param);
        if (pageSize < 0 || pageSize > 2000) {
            pageSize = Page.DEFAULT_PAGE_SIZE;
        }
        if (start == -1) {
            throw new RuntimeException("参数不正确 !!");
        }
        if (!iSecurity.isControl(userLoginId,"organChain","SELECT")) {
            return dao.queryPage(UserExpertEntity.class.getName() + ".selectSupportUser", param, start, pageSize);
        } else {
            Set<String> dataObjectIds = iSecurity.findDataObjectIds(userLoginId,"organChain","SELECT");
            if (UtilValidate.isEmpty(dataObjectIds)) {
                return new Page<>();
            }
            param.put("dataObjectIds", dataObjectIds);
            return dao.queryPage(UserExpertEntity.class.getName() + ".selectSupportUser", param, start, pageSize);
        }
    }


    /**
     * 多条件查询结果不分页
     */
    public List<?> find(Map<String, Object> map) {
        logger.debug("find {}", map);
        return dao.queryForList(UserExpertEntity.class.getName() + ".selectByMap", map);
    }

    /**
     * 根据部门，标签，获取所有专家
     *
     * @param departId
     * @param expertTag
     * @return
     */
    public List<String> findExpertIds(String departId, String expertTag) {
        List<IDictionaryTreeData> datas = dictionayTreeServiceProxy.getTreeDataChain("support-type",expertTag);
        if (datas.size() >= 2) {
            expertTag = datas.get(1).getCode();
        }
        if (datas.size() == 1) {
            expertTag = datas.get(0).getCode();
        }
        Map<String,Object> params = new HashMap<>();
        params.put("departId",departId);
        params.put("expertTag",expertTag);
       List<UserExpertEntity> entities = (List<UserExpertEntity>) dao.queryForList(UserExpertEntity.class.getName() + ".selectMulitCondition",params);

        return entities.stream().map(UserExpertEntity::getUserId).collect(Collectors.toList());
    }

    /**
     * 根据组织，标签获取所有支撑人员
     *
     * @param organId
     * @param expertTag
     * @return
     */
    public List<String> findSupportManager(String organId, String expertTag,String roleId,int limit) {
        List<IDictionaryTreeData> datas = dictionayTreeServiceProxy.getTreeDataChain("support-type",expertTag);
        List<String> tags = datas.stream().map(IDictionaryTreeData::getCode).collect(Collectors.toList());
        // 自动派单精确分级匹配，要凑够3个人
        logger.info("auto send order support-type: {}",tags);
        List<String> result = new ArrayList<>(5);
        String tag = tags.get(tags.size()-1);
        Map<String,Object> params = new HashMap<>();
        params.put("organId",organId);
        params.put("roleId",roleId);
        while (result.size() < 5 && tags.indexOf(tag) >= 1) {
            params.put("tag",tag);
            Page<Map<String,Object>>  page = dao.queryPage(UserExpertEntity.class.getName() + ".findSupportorByDepartAndExpertTags",params,0,limit);
            List<String> temp = page.getResult().stream().map(map -> (String) map.get("USERID")).collect(Collectors.toList());
            result.addAll(temp);
            tag = tags.get(tags.indexOf(tag)-1);
        }
        logger.warn("自动派单人员列表：{}",result.stream().collect(Collectors.joining(",")));
        return result;
    }

}
